package org.game.porker.porker24.controller;

//import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.game.porker.porker24.mybatis.pojo.Player;
import org.game.porker.porker24.mybatis.service.PlayerService;
import org.game.porker.porker24.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/player")
public class PlayerController {
	private static Logger logger = Logger.getLogger(PlayerController.class);
	@Autowired
	private PlayerService playerService;

	public PlayerController() {
		// TODO Auto-generated constructor stub
	}
	
	@RequestMapping("/register")//跳转注册页面
	public String register() {
		return "register";
	}
	
	@RequestMapping("/saveReg")//保存玩家注册信息
	public String saveReg(HttpServletRequest request){
		String loginName = request.getParameter("loginName");
		String pass = request.getParameter("password");
		Player pl = new Player();
		pl.setLoginName(loginName);
		pl.setPassword(pass);
		pl.setAvgScore(0);
		try {
			playerService.addNewPlayer(pl);
		}catch (Exception e) {
			logger.error(e.getMessage(), e);
			return "redirect:register";
		}
		request.getSession().setAttribute(ConstantUtil.playerInSessionKey, pl);
		return "redirect:/home/index";
	}
	
	@RequestMapping("/logout")//登出
	public String logout(HttpServletRequest request) {
		request.getSession().invalidate();
		return "redirect:/home/index";
	}
	
	@RequestMapping("/login") //跳转登录页面
	public String login() {
		return "login";
	}
	
	@RequestMapping("/tryLogin")//登录
	public String tryLogin(HttpServletRequest request) {
		String loginName = request.getParameter("loginName");
		String pass = request.getParameter("password");
		Player player = null;
		try {
			player = playerService.playerLogin(loginName, pass);
			if(player == null) {
				throw new Exception("no Match");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return "redirect:login";
		}
		request.getSession().setAttribute(ConstantUtil.playerInSessionKey,
				player);
		return "redirect:/home/index";
	}

}
